package oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.*;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Map;

public class OSSTest1 {
    private final Logger logger = LoggerFactory.getLogger(OSSTest1.class);

    // 访问域名
    private static String endpoint = "oss-cn-shenzhen.aliyuncs.com";
    // 访问密钥（简称AK,指访问身份验证中用到的AccessKeyId和 AccesskeySecret,AccessKeyId用于标识用户；AccessKeySecret是用户用于加密签名字符串和OSS用来验证签名字符串的密钥，必须保密。）
    private static String accessKeyId = "LTAI5tQKxGhb8RugsY2keJSH";
    private static String accessKeySecret = "zFGlHouBRqacksmkQhceq0gOMhg6SQ";
    private static String bucketName = "example-bucket-shg-1";
    // key就是文件名称（此处先随便写一个，真正用到时，获取当前上传的文件名称赋值给key）
    private static String key = "learning";

    @Test
    public void test1() throws Exception {

        // 创建客户端实例，连接到OSS服务端，需要提供访问域名endpoint,accessKeyId,accessKeySecret
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        logger.info("Getting Started...");

        // 列出当前账户下所有的bucket
        listAllBucket(ossClient);

        // 创建新的Bucket
        createNewBucket(ossClient, bucketName);
        // 获取创建的Bucket信息
        getBucketInfo(ossClient, bucketName);

        // 上传文件到Bucket
        uploadFileToBucket(ossClient, getFile());

        // 下载文件
        downloadFileFromBucket(ossClient, getFile().getName());
        ossClient.shutdown();
        
        // 获取指定文件的下载链接
        //getLink(ossClient,)
        System.out.println("----------------");
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        URL url = ossClient.generatePresignedUrl(bucketName, getFile().getName(),expiration);
        //GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, getFile().getName());
        //URL url1 = ossClient.generatePresignedUrl(new GeneratePresignedUrlRequest(bucketName, getFile().getName()));
        System.out.println("url: "+url);
    }
    
    @Test
    public void test2(){

        // 访问域名
        String endpoint = "oss-cn-shenzhen.aliyuncs.com";
        // 访问密钥（简称AK,指访问身份验证中用到的AccessKeyId和 AccesskeySecret,AccessKeyId用于标识用户；AccessKeySecret是用户用于加密签名字符串和OSS用来验证签名字符串的密钥，必须保密。）
        String accessKeyId = "LTAI5tQKxGhb8RugsY2keJSH";
        String accessKeySecret = "zFGlHouBRqacksmkQhceq0gOMhg6SQ";
        String bucketName = "xxx-shg-test";
        // key就是文件名称（此处先随便写一个，真正用到时，获取当前上传的文件名称赋值给key）

        // 创建客户端实例，连接到OSS服务端，需要提供访问域名endpoint,accessKeyId,accessKeySecret
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        URL url = ossClient.generatePresignedUrl(bucketName, "testFile/DCIM(4).jpg", expiration);
        System.out.println(url);
    }
    

    private void getBucketInfo(OSS ossClient, String bucketName) {
        BucketInfo bucketInfo = ossClient.getBucketInfo(bucketName);
        System.out.println("-----");
        // 获取地域。
        System.out.println(bucketInfo.getBucket().getLocation());
        // 获取创建日期。
        System.out.println(bucketInfo.getBucket().getCreationDate().toLocaleString());
        // 获取拥有者信息。
        System.out.println(bucketInfo.getBucket().getOwner());
        // 获取容灾类型。
        System.out.println(bucketInfo.getDataRedundancyType());
        System.out.println("-----");
    }

    private void downloadFileFromBucket(OSS ossClient, String key) throws Exception {
        if (ossClient.doesObjectExist(bucketName, key)) {
            OSSObject object = ossClient.getObject(bucketName, key);
            // 输出对象的元信息
            printObjectMetadata(object.getObjectMetadata());
            // 把对象保存到本地指定位置
            storageFile(object.getObjectContent());
        }
    }

    /**
     * @param objectContent 下载的文件流
     * @throws Exception exception
     */
    private void storageFile(InputStream objectContent) throws Exception {
        File file = new File("C:\\Users\\hz21076971\\Desktop\\Desktop\\picture\\download\\"+getFile().getName());
        BufferedInputStream bufferedInputStream = new BufferedInputStream(objectContent);
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
        byte[] b = new byte[1024];
        while (bufferedInputStream.read(b) != -1) {
            bufferedOutputStream.write(b);
        }
        bufferedOutputStream.flush();
    }


    /**
     * 输出对象的元信息
     *
     * @param objectMetadata 对象元信息对象
     */
    private void printObjectMetadata(ObjectMetadata objectMetadata) {
        Map<String, Object> rawMetadata = objectMetadata.getRawMetadata();
        rawMetadata.forEach((k, v) -> System.out.println(k + "---" + v));
    }

    /**
     * 获取要上传文件
     *
     * @return 返回要上传的文件
     */
    private File getFile() {
        return new File("C:\\Users\\hz21076971\\Desktop\\Desktop\\picture\\驾驶证照片.jpg");
    }

    /**
     * 上传文件到Bucket
     *
     * @param ossClient OSS client instance
     * @param file      File object to read from.
     */
    private void uploadFileToBucket(OSS ossClient, File file) throws FileNotFoundException {
        logger.info("开始上传文件:{} 到 {}", file.getName(), bucketName);
        long beginUploadTime = System.currentTimeMillis();
        PutObjectResult putObjectResult = ossClient.putObject(bucketName, file.getName(), file);
        ResponseMessage response = putObjectResult.getResponse();
        String uri = response.getUri();
        System.out.println("*********uri "+uri);
        ossClient.putObject(bucketName, file.getName(), new BufferedInputStream(new FileInputStream(file)));
        
        
        long endUploadTime = System.currentTimeMillis();
        logger.info("结束上传文件:{} 到 {},耗时{}ms", file.getName(), bucketName, endUploadTime - beginUploadTime);
        
    }

    /**
     * 创建新的Bucket
     *
     * @param ossClient  OSS 客户端实例对象
     * @param bucketName Bucket 名称
     */
    private void createNewBucket(OSS ossClient, String bucketName) {
        if (!ossClient.doesBucketExist(bucketName)) {
            logger.info("开始创建新的Bucket:{}", bucketName);
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            //createBucketRequest.setStorageClass(StorageClass.Standard);
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(createBucketRequest);
            logger.info("结束创建新的Bucket:{}", bucketName);
        }
    }

    /**
     * 列出当前账户下所有的Bucket
     */
    private void listAllBucket(OSS ossClient) {
        ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
        listBucketsRequest.setMaxKeys(500);
        for (Bucket bucket : ossClient.listBuckets()) {
            System.out.println("Bucket Name: " + bucket.getName());
        }
    }

}
